local CheckWidgetType = UI.CheckWidgetType
local CheckArgType = UI.CheckArgType

function UI.RegisterScriptHandlers(class, ...)
	local scripts
	class.scripthandlers = {}

	for i = 1, select("#", ...) do
		local event = select(i, ...)
		class.scripthandlers[event] = true
	end
	local name = class.name

	function class.prototype:SetScript(event, func)
		CheckWidgetType(name..":SetScript", self, name)
		CheckArgType(name..":SetScript", 2, "event", "string", event)
		CheckArgType(name..":SetScript", 3, "func", {"function" , "nil"}, func)
		local p = UI.params[self]
		if not self:HasScript(event) then
			log("EE SETSCRIPT : %s, %s, %s", p.name, name, event)
		end
		local s = p.scripts
		if not s then
			s = {}
			p.scripts = s
		end
		s[event] = func
		if func then
			Security:setobject(func)
		end
	end

	local function has_script(class, event)
		if class.scripthandlers and class.scripthandlers[event] then return true end
		local parent = class.parent
		if not parent then return false end
		if type(parent) == "string" then
			return has_script(UI.objects[parent], event)
		else
			for _, p in ipairs(parent) do
				if has_script(UI.objects[p], event) then return true end
			end
		end
	end

	function class.prototype:HasScript(event)
		CheckWidgetType(name..":HasScript", self, name)
		CheckArgType(name..":HasScript", 2, "event", "string", event)
		return has_script(class, event)
	end

	function class.prototype:GetScript(event, func)
		CheckWidgetType(name..":GetScript", self, name)
		CheckArgType(name..":GetScript", 2, "event", "string", event)
		if not self:HasScript(event) then
			print("GETSCRIPT :", name, event)
		end
		local s = UI.params[self].scripts
		return s and s[event]
	end

	function class.prototype:HookScript(event, func)
		CheckWidgetType(name..":HookScript", self, name)
		CheckArgType(name..":HookScript", 2, "event", "string", event)
		CheckArgType(name..":HookScript", 3, "func", "function" , func)
		local p = UI.params[self]
		if not self:HasScript(event) then
			log("EE HOOKSCRIPT : %s, %s, %s", p.name, name, event)
		end
		local s = p.scripthooks
		if not s then
			s = {}
			p.scripthooks = s
		end
		local t = s[event]
		if not t then
			t = {}
			s[event] = t
		end
		table.insert(t, func)
		Security:setobject(func)
	end
end
